// websocket.js
// import store from "@/store/index.js"
// import { getToken } from "@/utils/auth";
let socketTask = null;
let meClose = false;
let url = "ws://localhost:8800/websocket/user/";
let token = null;
let Time = null;
let XTime = null;
let reconnectCount = 0; // 添加重连计数器
const MAX_RECONNECT_ATTEMPTS = 10; // 最大重连次数
const RECONNECT_INTERVAL = 3000; // 重连时间间隔，单位为毫秒

const socket = (callback) => {
    // 获取token，根据实际存储方式修改
    //   token = getToken();
    token = sessionStorage.getItem('token');
    console.log("qttoken", token);
    console.log(url + token);

    if (socketTask) {
        socketTask.close();
        socketTask = null;
    }

    socketTask = new WebSocket(url + token);

    socketTask.onopen = () => {
        console.log("连接成功！获取离线信息");
        clearInterval(Time);
        clearInterval(XTime);

        let pin = {
            type: "ping"
        };
        sendMsg(pin);

        XTime = setInterval(() => {
            sendMsg(pin);
        }, 5000);
    };

    socketTask.onerror = (err) => {
        console.log('连接失败，请检查', err);
        if (!meClose) {
            reconnect();
        }
    };

    socketTask.onclose = (e) => {
        console.log('连接关闭！', meClose);
        if (!meClose) {
            reconnect();
        }
    };

    socketTask.onmessage = (res) => {
        let data = JSON.parse(res.data);
        console.log('服务器内容:', data);
        // 将接收到的数据传递给 callback
        if (callback) {
            callback(data);
        }
    };
};

const reconnect = () => {
    if (reconnectCount >= MAX_RECONNECT_ATTEMPTS) {
        console.log("重连次数超过最大限制，不再重连！");
        meClose = true;
        clearInterval(Time);
        return;
    }
    console.log("开始断线重连！", reconnectCount + 1);
    reconnectCount++;// 重连次数加1
    if (socketTask) {
        socketTask.close();
        socketTask = null;
    }
    console.log("重新连接中...");
    setTimeout(() => {
        socket(url + token);
    }, RECONNECT_INTERVAL);// 重连时间间隔
};

const sendMsg = (msg) => {
    msg = JSON.stringify(msg);
    console.log(msg, '向后端发送数据');

    if (socketTask && socketTask.readyState === WebSocket.OPEN) {
        socketTask.send(msg);
    } else {
        console.log("发送失败");
        // 使用 Vue 的消息提示，需要在 Vue 组件中使用
        // this.$message.loading('加载中...', 1);
        if (!meClose) {
            reconnect();
        }
    }
};

const stop = () => {
    meClose = true;
    if (socketTask) {
        socketTask.close();
        console.log("手动关闭成功！");
        clearInterval(Time);
        clearInterval(XTime);
        socketTask = null;
    }
};

export const websocketObj = {
    socket,
    stop,
    sendMsg
};